package com.jiuyou.storeController.store;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.adapayBalanceRecord.domain.AdapayBalanceRecord;
import com.ruoyi.clerkBalance.domain.ClerkBalance;
import com.ruoyi.clerkBalance.service.IClerkBalanceService;
import com.ruoyi.clerkBalanceRecord.domain.ClerkBalanceRecord;
import com.ruoyi.clerkBalanceRecord.service.IClerkBalanceRecordService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.staff.domain.Staff;
import com.ruoyi.staff.service.IStaffService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.util.CommonUtil;
import com.ruoyi.wechat.util.ConstantWeChat;
import com.ruoyi.wechat.util.TokenUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/store/user")
@Api(tags = {"员工控制器"})
public class StoreUserTController extends StoreBaseController {

    @Autowired
    private IClerkBalanceService clerkBalanceService;
    @Autowired
    private IClerkBalanceRecordService clerkBalanceRecordService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IStaffService staffService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private CommonUtil commonUtil;

    /**
     * 员工首页
     * */
    @PostMapping("/getIndexData")
    public AjaxResult getIndexData(){
        JSONObject j = new JSONObject();
        j.put("success",false);
        j.put("msg","失败");

        Long userId = getLoginStoreUserId();
        ClerkBalance clerkBalance = clerkBalanceService.selectClerkBalanceByStoreUserId(userId);

        ClerkBalanceRecord clerkBalanceRecord = new ClerkBalanceRecord();
        clerkBalanceRecord.setStoreUserId(userId);
        clerkBalanceRecord.setBusType("pro");
        List<ClerkBalanceRecord> ClerkBalanceRecordList = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord);
        BigDecimal proPrice = BigDecimal.ZERO;
        //自身收入
        for(ClerkBalanceRecord cbr: ClerkBalanceRecordList){
            proPrice = proPrice.add(cbr.getMoney());
        }

        ClerkBalanceRecord clerkBalanceRecord2 = new ClerkBalanceRecord();
        clerkBalanceRecord2.setStoreUserId(userId);
        clerkBalanceRecord2.setBusType("blet");
        List<ClerkBalanceRecord> ClerkBalanceRecordList2 = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord2);
        BigDecimal bletPrice = BigDecimal.ZERO;
        //老带新收入
        for(ClerkBalanceRecord cbr2: ClerkBalanceRecordList2){
            bletPrice = bletPrice.add(cbr2.getMoney());
        }

//        System.out.println("自身收入");
//        System.out.println(proPrice);
        j.put("success",true);
        j.put("msg","成功");
        j.put("commission", clerkBalance.getCommission());//项目佣金
        j.put("balance", clerkBalance.getBalance());//分销佣金
        j.put("proPrice", proPrice);//自身收入
        j.put("bletPrice", bletPrice);//老带新收入

        return AjaxResult.success(j);
    }


    /**
     * 佣金明细
     * */
    @PostMapping("/getcCommissionData")
    public AjaxResult getcCommissionData(){
        JSONObject j = new JSONObject();
        j.put("success",false);
        j.put("msg","失败");

        Long userId = getLoginStoreUserId();
        ClerkBalance clerkBalance = clerkBalanceService.selectClerkBalanceByStoreUserId(userId);

        ClerkBalanceRecord clerkBalanceRecord = new ClerkBalanceRecord();
        clerkBalanceRecord.setStoreUserId(userId);
        clerkBalanceRecord.setBusType("pro");
        List<ClerkBalanceRecord> ClerkBalanceRecordList = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord);
        BigDecimal proPrice = BigDecimal.ZERO;
        //自身收入
        for(ClerkBalanceRecord cbr: ClerkBalanceRecordList){
            proPrice = proPrice.add(cbr.getMoney());
        }

        ClerkBalanceRecord clerkBalanceRecord2 = new ClerkBalanceRecord();
        clerkBalanceRecord2.setStoreUserId(userId);
        clerkBalanceRecord2.setBusType("blet");
        List<ClerkBalanceRecord> ClerkBalanceRecordList2 = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord2);
        BigDecimal bletPrice = BigDecimal.ZERO;
        //老带新收入
        for(ClerkBalanceRecord cbr2: ClerkBalanceRecordList2){
            bletPrice = bletPrice.add(cbr2.getMoney());
        }

        //推广收入
        ClerkBalanceRecord clerkBalanceRecord4 = new ClerkBalanceRecord();
        clerkBalanceRecord4.setStoreUserId(userId);
        clerkBalanceRecord4.setBusType("push");
        List<ClerkBalanceRecord> ClerkBalanceRecordList3 = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord4);
        BigDecimal pushPrice = BigDecimal.ZERO;
        //老带新收入
        for(ClerkBalanceRecord cbr2: ClerkBalanceRecordList2){
            pushPrice = pushPrice.add(cbr2.getMoney());
        }


        //佣金详情
        ClerkBalanceRecord clerkBalanceRecord3 = new ClerkBalanceRecord();
        clerkBalanceRecord3.setStoreUserId(userId);
        startPage();
        List<ClerkBalanceRecord> clerkBalanceRecordListAll = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord3);

        j.put("success",true);
        j.put("msg","成功");
        j.put("commission", clerkBalance.getCommission());//项目佣金
        j.put("proPrice", proPrice);//自身收入
        j.put("bletPrice", bletPrice);//老带新收入
        j.put("pushPrice", pushPrice);//推广收入
        j.put("clerkBalanceRecordListAll", getDataTable(clerkBalanceRecordListAll));//佣金详情

        return AjaxResult.success(j);
    }

    /**
     * 我的分销
     * */
    @RequestMapping("/getData")
    public AjaxResult getData(){
        Long storeUserId = getLoginStoreUserId();
        BigDecimal yesterday = BigDecimal.ZERO;
        BigDecimal count = BigDecimal.ZERO;
        yesterday = clerkBalanceRecordService.selectData(storeUserId,new Date());
        count = clerkBalanceRecordService.selectData(storeUserId,null);
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("yesterday", Arith.numTostr(yesterday));
        map.put("count",Arith.numTostr(count));
        return AjaxResult.success(map);
    }

    /**
     * 我的客户
     * */
    @RequestMapping("/getMyMember")
    public AjaxResult getMyMember(){
        Long storeUserId = getLoginStoreUserId();
        System.out.println("tang1");
        System.out.println(storeUserId);
        Member member = new Member();
        member.setStoreUserId(storeUserId);
        startPage();
        List<Member>  list = memberService.selectMemberList(member);
        TableDataInfo tableDataInfo= getDataTable(list);
        return AjaxResult.success(tableDataInfo);
    }

    /**
     * 分销明细
     * */
    @RequestMapping("/getCommissionList")
    public AjaxResult getCommissionList(){
//        StoreUserRole storeUserRole = getStoreUserRole();
//        Long storeId = storeUserRole.getStoreId();
//        AdapayBalanceRecord adapayBalanceRecord = new AdapayBalanceRecord();
//        adapayBalanceRecord.setStoreId(storeId);
//        adapayBalanceRecord.setBusType(DicConstants.BUSTYPE_BALANCE_DIV.getCode());
        Long storeUserId = getLoginStoreUserId();
        ClerkBalanceRecord clerkBalanceRecord = new ClerkBalanceRecord();
        clerkBalanceRecord.setStoreUserId(storeUserId);
        clerkBalanceRecord.setBusType(DicConstants.BUSTYPE_BALANCE_DIV.getCode());
        startPage();
        List<ClerkBalanceRecord> list = clerkBalanceRecordService.selectClerkBalanceRecordList(clerkBalanceRecord);
        TableDataInfo tableDataInfo= getDataTable(list);
        JSONArray jsonArray=JSONArray.parseArray(JSONArray.toJSONString(list));
        for (Object o : jsonArray) {
            JSONObject jso=(JSONObject)o;
            jso.put("money", Arith.numTostr(jso.getBigDecimal("money")));
            jso.put("createTime", DateUtils.dateTimeYMDHSM(jso.getDate("createTime")));
        }
        tableDataInfo.setRows(jsonArray);
        return AjaxResult.success(tableDataInfo);
    }


    /**
     * 刷新推广二维码
     * */
    @RequestMapping("/refreshStoreBelow")
    public AjaxResult refreshStoreBelow(){
        Long storeUserId = getLoginStoreUserId();
        storeBelow(storeUserId);//绑定为下级二维码

        Staff staff =  staffService.selectStaffById(storeUserId);
        return AjaxResult.success(staff);
    }

    public String storeBelow(Long storeUserId){
//        Staff staff = staffService.selectStaffById(storeUserId);
//        String belowImageUrl=staff.getBelowImageUrl();
//        if(!StringUtils.isEmpty(belowImageUrl)){
//            return belowImageUrl;
//        }
        //long userId = getLoginStoreUserId();
        String APPKEY="YQS_C";
        String requrl= serverConfig.getUrl();
        JSONObject param=new JSONObject();
        String qrcodePage="";
        String scene="";
        String page="";
        //图书，进入章节目录
        scene="storeUserId="+storeUserId;
        page="pages/UCenter/index/index";
        param.put("scene",scene);
        param.put("page",page);
        qrcodePage=page+"?"+scene;
        String pro_env=sysConfigService.selectConfigByKey(DicConstants.PRO_ENV.getCode());
        if(null==pro_env){
            return null;
        }
//        param.put("env_version","develop");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
//        param.put("check_path",false);
        //System.out.println(pro_env);
        if(DicConstants.SYS_Y.getCode().equals(pro_env)){
            System.out.println("正式");
            //正式环境
            param.put("env_version","release");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
        }else{
            System.out.println("体验");
            //测试参数，体验版使用，不要在正式使用
            param.put("env_version","trial");//正式版为 "release"，体验版为 "trial"，开发版为 "develop"
            param.put("check_path",false);
        }
        String codeName=storeUserId+"_commission_"+ IdUtils.fastUUID();
        String xml = JSONObject.toJSONString(param);
        String requestUrl= ConstantWeChat.GET_WX_ACODE_UNLIMIT.replace("#ACCESS_TOKEN#", tokenUtil.getToken(APPKEY).getAccessToken());
        JSONObject resultR= commonUtil.doPostFile(requestUrl,xml,codeName,requrl);
        if(resultR.containsKey("imgUrl")){
            String imgUrl=resultR.getString("imgUrl");
            String fileAbsolutePath=resultR.getString("fileAbsolutePath");

            Staff updateStaff = new Staff();
            updateStaff.setId(storeUserId);
            updateStaff.setBelowImageLocal(fileAbsolutePath);
            updateStaff.setBelowImageUrl(imgUrl);
            updateStaff.setBelowPage(qrcodePage);
            staffService.updateStaff(updateStaff);
            return imgUrl;
        }
        return null;
    }
}
